<template>

  <div class="filter-container">

    <el-form
            :inline="true"
            :model="formData"
            label-position="right"
            size="small"
            class="filter-form-inline"
    >
      <el-row
              :gutter="20"
              style="margin-left: 0px; margin-right: 0px"
      >
        <el-col
                :span="6"
        >
          <el-form-item
                  label="状态"
                  style="width: 100%"
          >
            <el-select
                    v-model="formData.status"
                    clearable
                    style="width: 100%"
                    placeholder="请选择状态"
                    @change="listSearch"
                    @clear="listSearch"
            >
              <el-option
                      v-for="item in statusOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col
                :span="6"
        >
          <el-form-item
                  label="规划地区"
                  style="width: 100%"
          >
            <el-cascader
                    :show-all-levels="false"
                    v-model="formData.area"
                    style="width: 100%;"
                    :options="citys"
                    placeholder="请选择适用地区"
                    :props="{ checkStrictly : true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
                    @change="areaChange"
            />
          </el-form-item>

        </el-col>

        <el-col
                :span="6"
        >
          <el-form-item
                  label="跟进职员"
                  style="width: 100%"
          >
            <el-select
                    v-model="formData.headId"
                    clearable
                    style="width: 100%"
                    placeholder="请选择职员"
                    @change="listSearch"
            >
              <el-option
                      v-for="item in headOptions"
                      :key="item.id"
                      :label="item.realName"
                      :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col
                :span="6"
        >
          <el-form-item style="width: 100%">
            <el-button
                    class="border-btn"
                    @click="reset"
            >重置</el-button>
            <el-button
                    type="primary"
                    class="main-btn"
                    @click="listSearch"
            >搜索</el-button>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

  </div>

  <table-view
          :data="tableData"
          @row-click="rowClick"
  >
    <el-table-column
            show-overflow-tooltip
            align="left"
            header-align="center"
            prop="planInfo.productPopularName"
            label="通用名"
            :min-width="150"
    />
    <el-table-column
            show-overflow-tooltip
            align="center"
            header-align="center"
            prop="planInfo.productName"
            label="商品名"
            :min-width="100"
    />
    <el-table-column show-overflow-tooltip align="center" header-align="center" prop="planInfo.packSpecs" label="包装规格" :min-width="100"/>
    <el-table-column show-overflow-tooltip align="center" header-align="center" prop="planInfo.producer" label="生产厂家" :min-width="100"/>
    <el-table-column
            align="center"
            header-align="center"
            label="规划招商地区"
            :min-width="150"
    >
      <template #default="{row}">
        {{row.planDetail?.areaName ? row.planDetail?.cityName + "/" + row.planDetail?.areaName : row.planDetail?.cityName ? row.planDetail?.cityName : row.planDetail?.provinceName}}
      </template>
    </el-table-column>
    <el-table-column
            align="center"
            header-align="center"
            label="代理周期"
            :min-width="100"
    >
      <template #default="scope">
        {{scope.row.planDetail?.agentCycle}}年
      </template>
    </el-table-column>
    <el-table-column
            show-overflow-tooltip
            align="center"
            header-align="center"
            label="最低销量"
            :min-width="100"
    >
      <template #default="scope">
        <span v-if="scope.row.planDetail?.isIncrease == 1">{{scope.row.planDetail?.minSale}}{{getLabel('sell_unit',scope.row.planDetail?.sellUnit)}}/年</span>
        <span v-else>首年{{scope.row.planDetail?.minSale}}{{getLabel('sell_unit',scope.row.planDetail?.sellUnit)}},每年递增{{scope.row.planDetail?.increaseNum}}%</span>
      </template>
    </el-table-column>
    <el-table-column
            align="center"
            header-align="center"
            label="销量保证金(元)"
            :min-width="150"
    >
      <template #default="scope">
        {{scope.row.planDetail?.sellEarnestMoney}}
      </template>
    </el-table-column>
    <el-table-column align="left" header-align="center" label="其他说明" prop="planDetail.remark" :min-width="150" show-overflow-tooltip/>
    <el-table-column header-align="center" align="center" label="跟进职员" prop="allocationAgent.headName"/>
    <el-table-column
            header-align="center"
            align="center"
            label="开发跟进期限"
            :min-width="140"
    >
      <template #default="scope">
        {{getDate(scope.row)}}
<!--        {{dateFormat('yyyy-mm-dd',scope.row.planInfo?.expireTime)}}-->
      </template>
    </el-table-column>
    <el-table-column
            align="center"
            header-align="center"
            label="状态"
            fixed="right"
            :min-width="150"
    >
      <template #default="scope">
        {{getStatus(scope.row)}}
<!--        {{getLabel('signed_plan_detail_status',scope.row.planDetail?.detailStatus)}}-->
      </template>
    </el-table-column>
    <el-table-column
            align="center"
            header-align="center"
            label="操作"
            fixed="right"
            :min-width="200"
    >
      <template #default="{row}">
        <el-button
                type="text"
                @click="onEditorial(row)"
        >推荐代理</el-button>
        <el-button
                v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                type="text"
                @click="onAccepted(row)"
        >接受</el-button>
        <el-button
                v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                type="text"
                @click="onReject(row)"
        >拒绝</el-button>
        <el-button
                v-auth="{v:['crm:marketing:planSigned:allocation'],bool:row.planDetail?.detailStatus == 0 || row.planDetail?.detailStatus == -3 || row.planDetail?.detailStatus == -4}"
                type="text"
                @click="onAllocation(row)"
        >分配</el-button>
<!--        <el-button-->
<!--                v-if="row.planDetail?.detailStatus == 1 && userInfo.ID == row.allocationAgent?.headId"-->
<!--                type="text"-->
<!--                @click="addAgreement(row)"-->
<!--        >代理协议签约</el-button>-->
      </template>
    </el-table-column>
  </table-view>

  <Pagination
          v-model:page="formData.page"
          v-model:limit="formData.pageSize"
          style="display: flex; justify-content: flex-end"
          :total="total"
          @pagination="getList"
  />

<!--  <allocationDialog ref="allocationDialog" @success="getList"></allocationDialog>-->

<!--  <addAgreementDialog ref="agreementDialog"/>-->

<!--  <rejectDialog ref="rejectDialog" @success="getList"/>-->

</template>

<script>
import {dateFormat} from "../../../../../../../utils/date";
// import rejectDialog from "./rejectDialog";
// import allocationDialog from "./allocationDialog";
import {crmStore} from "../../../../../store";
import {useRouter} from 'vue-router'
import area from "../../../../../../../utils/area";
import {defineComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs} from 'vue'

export default defineComponent({
    name: "index",
    emits:['onAllocation','onReject'],
    components:{
      // allocationDialog,
      // addAgreementDialog: defineAsyncComponent(() =>
      //         import('../../../modules/addAgreementDialog.vue')
      // ),
      // rejectDialog
    },
    setup(props,{emit}){
      const router = useRouter()
      const currentInstance = getCurrentInstance()
      const api = inject('api')
      const citys = area
      const userInfo = crmStore.getters['user/userInfo']
      const statusOption = ref([
        {
          label:'待分配',
          value:'1'
        },
        {
          label:'分配待确认',
          value:'2'
        },
        {
          label:'已拒绝',
          value:'3'
        },
        {
          label:'已分配',
          value:'4'
        },
        {
          label:'代理开发失败',
          value:'-4'
        }
      ])

      var data = reactive({
        tableData:[],
        formData:{
          listType:'1',
          planType:'2',
          page:1,
          pageSize:20,
          status:'',
          area:[],
        },
        total:0,
        headOptions:crmStore.getters['company/getHeadOptions'],
        allocationDialog:null,
        agreementDialog:null,
        userId:0,
        rejectDialog:null,
      })

      const listSearch = () => {
        data.formData.page = 1
        getList()
      }

      const reset = () => {
        data.formData = {
          listType:'1',
          planType:'2',
          page:1,
          pageSize:20,
          status:'',
          area:[],
        }
        getList()
      }

      const areaChange = () => {
        listSearch()
      }

      const onEditorial = (row) => {
        router.push({path:'/editorial/agent/create',query:{id:row.planDetail.id}})
      }

      const onAccepted = (row) => {
        currentInstance.proxy
                .alertBox({
                  message: '确认同意接受此任务？',
                  title: '接受',
                })
                .then(() => {
                  api.plan.ALLOCATION_AGENT_DEAL({planDetailId:row.planDetail.id,type:'1'}).then(res=>{
                    if (!res.code){
                      currentInstance.proxy.customMessage({type:'success',message:'处理成功'})
                      getList()
                    }else {
                      currentInstance.proxy.customMessage({type:'error',message:res.msg})
                    }
                  })
                })
                .catch((err) => {
                  console.log(err)
                })
      }

      const onReject = (row) => {
        // data.rejectDialog.open(row.planDetail.id)
        emit('onReject',row)
      }

      const addAgreement = (row) => {
        data.agreementDialog.open(1,row)
      }

      const getList = () => {
        let a = {...data.formData}
        if (a.area.length){
          if (a.area.length == 1){
            a.provinceCode = a.area[0]
          }else if (a.area.length == 2){
            a.cityCode = a.area[1]
          }else if (a.area.length == 3){
            a.areaCode = a.area[2]
          }
        }
        api.plan.PLAN_DETAIL_LIST(a).then(res=>{
          if (!res.code){
            data.total = res.data.total
            data.tableData = res.data.list || [];
          }else {
            currentInstance.proxy.customMessage({type:'error',message:res.msg})
          }
        })
      }

      const rowClick = (row,column) => {
        if (column.label === '操作') return
        router.push({name:'marketPlanDetail',query:{id:row.planDetail.id}})
      }

      const onAllocation = (row) => {
        // data.allocationDialog.open(row)
        emit('onAllocation',row)
      }

      const getStatus = (row) => {
        let str = ''

        switch (row.planDetail?.detailStatus) {
          case "0":
            str = '待分配';
            break;
          case "-2":
            str = '分配待确认';
            break;
          case "-3":
            str = '已拒绝';
            break;
          case "-4":
            str = '代理开发失败';
            break;
          case "-5":
            str = '终端开发失败';
            break;
          case "1":
            str = '已分配';
            break;
          case "2":
            str = '已分配';
            break;
          case "3":
            str = '已分配';
            break;
        }

        return str
      }

      const getDate = (row) => {

        if (row.allocationAgent && row.allocationAgent.allocationAgentDetails){
          let str = ''
          row.allocationAgent.allocationAgentDetails.forEach(item=>{
            if (!str){
              str = item.dealTime
            }else if (new Date(str).getTime() < new Date(item.dealTime)) {
              str = item.dealTime
            }
          })
          return dateFormat('yyyy-mm-dd',str)
        }else {
          return ''
        }

      }

      onMounted(() => {

        getList()
      })

      return{
        ...toRefs(data),
        statusOption,
        citys,
        userInfo,

        getList,
        rowClick,
        listSearch,
        reset,
        areaChange,
        onAllocation,
        addAgreement,
        onEditorial,
        getStatus,
        onAccepted,
        onReject,
        getDate,
      }
    }
  })
</script>

<style scoped>

</style>
